<?php
/**
 * DotHerbert
 *
 * @package    loader
 * @copyright  2009 extreme-programmers
 * @license    http://dotherbert.extreme-programmers.com/license   BSD License
 * @version    $Id:$
 */

namespace dotherbert\loader;

/**
 * Autoloader
 *
 * @package    loader
 * @author     Johannes Trink <johannes.trink@extreme-programmers.com>
 */
class Autoloader
{
    /**
     * Singleton instance
     *
     * @return self
     */
    private static $instance = null;

    /**
     * Autoloaders
     *
     * @var array
     */
    private $autoloaders = array();

    /**
     * Constructor
     *
     * @return void
     */
    private function __construct()
    {
        spl_autoload_register(array(__CLASS__, 'autoload'));
    }

    /**
     * Get instance
     *
     * @return Autoloader
     */
    public static function getInstance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Unset instance
     *
     * @return void
     */
    public static function unsetInstance()
    {
        self::$instance = null;
//        spl_autoload_unregister(array(__CLASS__, 'autoload'));
    }

    /**
     * Set instance
     *
     * @param Autoloader
     * @return void
     */
    public static function setInstance(Autoloader $instance)
    {
        self::$instance = $instance;
    }


    /**
     * Get autoloaders
     *
     * @return array
     */
    public function getAutoloaders()
    {
        return $this->autoloaders;
    }

    /**
     * Add autoloader
     *
     * @param AutoloaderInterface
     *
     * @return void
     */
    public function addAutoloader(AutoloaderInterface $autoloader)
    {
        $this->autoloaders[] = $autoloader;
    }

    /**
     * Autoload
     *
     * @param string $class
     * @return bool
     */
    public function autoload($class)
    {
        $self = self::getInstance();
        foreach ($self->getAutoloaders() as $autoloader) {
            if (true === $autoloader->autoload($class)) {
                return true;
            }
        }
        return false;
    }
}